import axios from "axios";
import React, { useEffect, useState } from "react";
import { Search, Tag, Space } from "react-vant";
import { FALSE } from "sass";
import { SearchState } from "../../types";
const Index: React.FC = () => {
  const [isSearch, setIsSearch] = useState(false);
  const [data, setData] = useState<SearchState[]>([]);
  const [list, setList] = useState<string[]>(
    JSON.parse(localStorage.getItem("list") || "[]")
  );
  const fetchSearch = async (value: string) => {
    const resp = await axios.get("/api/search/list", { params: { value } });
    setData(resp.data.data);
  };

  const addSearchHistory = (value: string) => {
    // 添加搜索记录
    const newList = [...new Set([value, ...list])];
    setList(newList);

    // 进行搜索
    fetchSearch(value);
    // 切换状态
    setIsSearch(true);
  };

  useEffect(() => {
    localStorage.setItem("list", JSON.stringify(list));
  }, [list]);

  return (
    <div className="search">
      <Search
        onSearch={(value) => addSearchHistory(value)}
        onClear={() => setIsSearch(false)}
      ></Search>
      {isSearch ? (
        <div>
          {data.map((v) => {
            return (
              <dl key={v.id}>
                <dt>
                  <img src={v.image} alt="" />
                </dt>
                <dd>
                  <h3>{v.title}</h3>
                  <div>{v.description}</div>
                </dd>
              </dl>
            );
          })}
        </div>
      ) : (
        <div className="history-search">
          <h3>历史搜索</h3>
          <div>
            <Space style={{ flexWrap: "wrap" }}>
              {list.map((v, i) => {
                return (
                  <Tag key={i} type="success">
                    {v}
                  </Tag>
                );
              })}
            </Space>
          </div>
        </div>
      )}
    </div>
  );
};

export default Index;
